#include <QSqlDatabase>
#include <QSqlQuery>
#include <QMessageBox>
#include <QStandardPaths>
#include <QDir>
#include <QDebug>

void createTables( QString &sqlLine)
{
    QSqlQuery query;
    query.exec(sqlLine);
    //qDebug()<<"Executing: "<<sqlLine;
    //qDebug()<<"\n\n\n";
}

void createDatabase()
{
    QFile f(":/sql/schema.sql");
    if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
        qDebug() << "cannot open resource file schema.sql";
    QTextStream in(&f);
    QString line;
    QString sqlStatement = "";
    while (!in.atEnd()){
        line = in.readLine();
        if(line.trimmed().startsWith('#') || line.isEmpty())
            continue;
        sqlStatement += line;
        if(sqlStatement.trimmed().endsWith(";")){
            createTables(sqlStatement);
            sqlStatement = "";
        }
    }
}

void populateDatabase(){

    QFile f(":/files/recipes.txt");
    if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
        qDebug() << "cannot open resorce file recipes.txt";
    QTextStream in(&f);
    QSqlQuery query;
    QString line;
    QString sqlPrefix = "INSERT INTO Recipe (name,recipe_type,preparation,dificulty,prep_time,vegetarian,cal_level,serves) VALUES";
    QString sqlStatement = "";
    int i=0;
    int c=1;
    int fi=0;

    QFile o("C:\\Users\\Jesus Gomez\\workspace\\Icemart\\out.txt");
    if(!o.open(QIODevice::WriteOnly | QIODevice::Text))
        qDebug()<<"cannot open output file";
    QTextStream out(&o);

    while(!in.atEnd())
    {
        line = in.readLine();
        if(line == "{"){
            sqlStatement+='(';
            i++;
            continue;
        }
        if(line == "}")
        {
            i=0;
            sqlStatement+=");"; 
            //qDebug()<<"executing" << sqlPrefix+sqlStatement;
            if(query.exec(sqlPrefix+sqlStatement)){
                qDebug()<<"sucessfully executed "<<c++;
                out<<"1:"+sqlStatement+'\n';
            }
            else{
                qDebug()<<"failed"<<fi++;
                out<<"0:"+sqlStatement+'\n';
            }
            sqlStatement="";
            continue;
        }
        switch (i) {
        case 1:
            sqlStatement+='\"'+line+"\",";
            break;
        case 2:
            sqlStatement+='\"'+line+"\",";
            break;
        case 3:
            sqlStatement+='\"'+line+"\",";
            break;
        case 4:
            sqlStatement+='\"'+line+"\",";
            break;
        case 5:
            sqlStatement+='\"'+line+"\",";
            break;
        case 6:
            if(line=="Si")
                sqlStatement+="1,";
            else if(line=="No")
                sqlStatement+="0,";
            else
                sqlStatement+="2,";
            break;
        case 7:
            sqlStatement+='\"'+line+"\",";
            break;
        case 8:
            if(line.toInt()!=0)
                sqlStatement+=line;
            else
                sqlStatement+="0";
            break;
        default:
            if(query.exec("INSERT INTO Ingredient (recipe_id,verbose_name) VALUES ("+QString::number(c)+",\""+line+"\");"))
            {
                qDebug()<<"Adding ingredient to recipe"<<c;
            }
            break;
        }
        i++;
    }
    f.close();

}

static bool createConnection()
{
    QString dataDir = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    QDir dir(dataDir);


    if(!dir.exists())
    {
        if(!dir.mkdir("."))
        {
            qDebug()<<"Error: creating directory";
        }
    }
    QString dbName = dir.filePath("Aplication.sqlite");

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbName);

    if (!db.open()) {
        QMessageBox::critical(0, qApp->tr("Error al iniciar la aplicacion"),
                              qApp->tr("Ha sido imposible encontrar los datos de aplicacion"),
                              QMessageBox::Ok);
        return false;
    }


    QString fileName = dir.filePath("log.txt");
    QFile f(fileName);
    QTextStream in(&f);
    if(!f.open(QIODevice::ReadWrite | QIODevice::Text))
        qDebug() << "cannot open resorce file recipes.txt";
    if(!(in.readLine()=="DONE"))
    {
        createDatabase();
        populateDatabase();
        in<<"DONE";
        f.close();
    }

    return true;
}


